package com.dykj.fireFighting.web.datasource;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * Created with IDEA
 *
 * @Author : HXB
 * @Date : 2021-09-23 10:47
 * @Description : 按日期分表解析
 **/
@Slf4j
public class DaysTableNameParser implements TableNameHandler {

    @Override
    public String dynamicTableName(String sql, String tableName) {
        // 获取参数方法
        if ("dev_his,dev_his_water,dev_his_zc".contains(tableName)) {
            log.info("=====分表查询按日期分表解析sql=====" + sql);
            Map<String, Object> paramMap = RequestDataHelper.getRequestData();
            if (CollectionUtils.isEmpty(paramMap)) {
                String dateDay = UUIDUtils.createYearWeek().substring(0, 6);
                log.info("=====分表查询的表名=====" + tableName + "_" + dateDay);
                return tableName + "_" + dateDay;
            }
            paramMap.forEach((k, v) -> log.info(k + "------------------------" + v));
            String id = String.valueOf(paramMap.get("id"));
            log.info("=====分表查询参数id值:=====" + id);
            if (StringUtils.isNotBlank(id) && id.length() > 6) {
                log.info("=====分表查询的表名:=====" + tableName + "_" + id.substring(0, 6));
                return tableName + "_" + id.substring(0, 6);
            }
        }
        return tableName;
    }
}
